package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.cache.service.BitmapService;
import com.atguigu.gmall.cache.service.CacheService;
import com.atguigu.gmall.common.consts.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.product.entity.SkuInfo;
import com.atguigu.gmall.product.service.SkuInfoService;
import com.atguigu.gmall.model.product.vo.SaveSkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author:lyd
 **/
@RestController
@RequestMapping("/admin/product")
public class SkuInfoController {

    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    CacheService cacheService;
    @Autowired
    BitmapService bitmapService;

    @PostMapping("/saveSkuInfo")
    public Result saveSkuInfo(@RequestBody SaveSkuInfoVo vo) {
        skuInfoService.saveSkuInfoDetail(vo);
        return Result.ok();
    }

    /**
     * 根据id下架商品
     * @param skuId
     * @return
     */
    @GetMapping("/cancelSale/{skuId}")
    public Result cancelSale(@PathVariable("skuId") Long skuId) {
        skuInfoService.lambdaUpdate()
                .set(SkuInfo::getIsSale, 0)
                .eq(SkuInfo::getId, skuId)
                .update();
        //从缓存中删除商品
        cacheService.delayDoubleDelete(RedisConst.SKU_INFO_CACHE_PREFIX + skuId, 1000L);
        //从位图中移除商品
        bitmapService.removeBitmap(RedisConst.BITMAP_SKUIDS, skuId);
        return Result.ok();
    }

    /**
     * 根据id上架商品
     * @param skuId
     * @return
     */
    @GetMapping("/onSale/{skuId}")
    public Result onlSale(@PathVariable("skuId") Long skuId) {
        skuInfoService.lambdaUpdate()
                .set(SkuInfo::getIsSale, 1)
                .eq(SkuInfo::getId, skuId)
                .update();
        //添加商品到位图中
        bitmapService.setBitmap(RedisConst.BITMAP_SKUIDS, skuId);
        //TODO 商品添加到检索系统
        return Result.ok();
    }

    /**
     * 初始化所有skuId到位图中
     * @return
     */
    @GetMapping("/init/skuIds/bitmap")
    public Result initSkuInfosBitmap() {
        skuInfoService.initSkuIdsBitmap();
        return Result.ok();
    }
}
